<?php

namespace common\services;

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

class AwsService
{
    private $s3;

    private $awsConfig;

    private $directory = "hipick-";

    public function __construct()
    {
        $this->awsConfig = \Yii::$app->params['aws_info'];
        $this->s3 = S3Client::factory(
            [
                'credentials' => [
                    'key' => $this->awsConfig['aws_key'],
                    'secret' => $this->awsConfig['secret']
                ],
                'version' => 'latest',
                'region' => $this->awsConfig['region']
            ]
        );
    }

    /**
     * 上传
     * @param $localFile
     * @param $newName
     * @return array|bool
     */
    public function uploadFileToAws($localFile, $newName)
    {

        $target_path = $this->directory . YII_ENV . '/' . $newName;

        $data = $this->putObject($localFile, $target_path);

        if (isset($data['ObjectURL'])) {
            $result = [
                'relative_url' => $data['ObjectURL'],
                'full_url' => $this->awsConfig['aws_host'] . '/' . $target_path
            ];

            return $result;
        }

        return false;
    }

    /**
     * 上传图片
     * @param $file_path
     * @param $target_path
     * @return \Aws\Result|string
     */
    private function putObject($file_path, $target_path)
    {
        $suffixInfo = explode('.', $target_path);
        $suffix = end($suffixInfo);
        $extensions = [
            'png' => 'png',
            'jpg' => 'jpeg',
            'jpeg' => 'jpeg',
            'gif' => 'gif',
            'bmp' => 'bmp'
        ];
        $res = $this->s3->putObject(
            [
                'Bucket' => trim($this->awsConfig['aws_bucket']),
                'Key' => $target_path,
                'SourceFile' => $file_path,
                'ContentType' => 'image/' . $extensions[$suffix],
                'ACL' => 'public-read',
                'StorageClass' => 'REDUCED_REDUNDANCY'
            ]
        );
        return $res;
    }

    /**
     * 删除图片
     * @param $file
     * @return \Aws\Result|bool|string
     */
    public function deleteObject($file)
    {
        // 获取文件的相对路径
        $file = str_replace($this->awsConfig['aws_host'], '', $file);
        try {
            $res = $this->s3->deleteObject(
                [
                    'Bucket' => trim($this->awsConfig['aws_bucket']),
                    'Key' => $file,
                ]
            );
            return $res;
        } catch (S3Exception $e) {
            return $e->getMessage();
        } catch (\Throwable $throwable) {
            return $throwable->getMessage();
        }
    }

}
